import util from '../util'
import style from './style.tip'

let tips = {}

export default () => {
  const fn = (el, msg, name) => {
    let scrollTop = 0
    let tip
    const isExist = tips[name]
    if (isExist) tip = tips[name].el
    else {
      tip = document.createElement('div')
    }
    const onScroll = scrollTop => {
      scrollTop = scrollTop
      update()
    }
    const onResize = () => update()
    if (!isExist) {
      tips[name] = {
        el: tip,
        listeners: {
          onScroll,
          onResize
        }
      }
    }
    tip.className = style.tip
    if (!isExist) {
      document.body.appendChild(tip)
    }

    update()

    function update() {
      const { left, top, width, height } = el.getBoundingClientRect()
      let dy, dx=5
      tip.textContent = msg
      tip.style.top = `${top}px`
      tip.style.left = `${left + width + dx}px`

      const { height: h } = tip.getBoundingClientRect()
      dy = (height - h)/2
      tip.style.top = `${top + dy - scrollTop}px`
      tip.style.opacity = 1
    }

    util.bus.on('page:scroll', onScroll)
    util.bus.on('page:resize', onResize)
  }
  fn.destroy = name => {
    if (tips[name]) {
      const { el, listeners } = tips[name]
      el.parentNode.removeChild(el)
      util.bus.off('page:scroll', listeners.onScroll)
      util.bus.off('page:resize', listeners.onResize)
      delete tips[name]
    }
  }
  fn.clear = () => {
    util.bus.off('page:scroll')
    util.bus.off('page:resize')
    for(var i in tips) {
      tips[i].el.parentNode.removeChild(tips[i].el)
    }
    tips = {}
  }
  return fn
}
